"use server";
import { promisePool } from "@/utils/mysql";
import { execSync } from "child_process";


export const generateJson = async (data: any, id: number) => {
  // 更新times表
  const [resu] = await promisePool.execute(
    "UPDATE `times` SET `time` = ?, `days` = ?, `email` = ?,`doctor` = ?,`doctorId` = ? WHERE `id` = ?",
    [data.times, data.days, data.email, data.docName, data.docId, 1]
  );
  if (resu) {
    return true;
  }
};

export const sqlDoctorList = async () => {
  const [resu] = await promisePool.execute("SELECT * FROM `doctors`");
  return resu;
};

export const getJson = async () => {
  const [resu] = await promisePool.execute(
    "SELECT * FROM `times` WHERE `id` = ?",
    [1]
  );
  if (resu && (resu as any).length === 1) {
    return (resu as any)[0];
  }
  return false;
  // const json = fs.readFileSync(process.env.JSON_LOCATION!, "utf8");
  // return json;
};

export const getPm2Status = async (processName: string) => {
  // 初始化 PM2 客户端
  const result = await execSync("pm2 list");
  const str = result.toString("utf-8");
  const lines = str.split("\n");
  const headerLine = lines[1]; // 获取表头行
  const dataLines = lines.slice(3, -1); // 获取数据行
  let ceshiColums = [];
  let found = false;
  let upTime = "";
  for (const line of dataLines) {
    const trimmedStr = line.trim().replace(/^│\s*|\s*│$/g, "");

    // 使用正则表达式匹配竖线及其周围的空白字符进行分割
    const columns = trimmedStr
      .split(/\s*│\s*/)
      .map((it) => it.trim().replace(/\u001b\[[0-9;]*m/g, ""));

    if (columns.includes(processName) && columns.includes("online")) {
      found = true;
      upTime = columns[6];
    }
  }
  return {
    // list: result.toString("utf-8"),
    // headerLine,
    // dataLines,
    // ceshiColums,
    status: found ? "online" : "offline",
    updateTIme: upTime,
  };
  //   const pm2 = await PM2({ target: "local" });
  //   return pm2.list;
};

export const reloadPm2 = async (processName: string) => {
  const result = await execSync(`pm2 restart ${processName}`);
  return result.toString("utf-8");
};
// 停止PM2进程
export const stopPm2 = async (processName: string) => {
  const result = await execSync(`pm2 stop ${processName}`);
  return result.toString("utf-8");
};
